package com.jk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jk.OrderBean;
import com.jk.UserBean;
import com.jk.UserInfo;
import com.jk.dao.USerDao;
import com.jk.service.UserService2;
import com.jk.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.data.domain.Sort.Order;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author 程旭航
 * @Create 2021/5/21 - 10:41
 * @Description
 */
@Service

public class UserServerImpl implements UserService2 {

    @Autowired
    private USerDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

/*    @Autowired
    private HttpSession session;*/




    /**
     * @Author:程旭航
     * @Description: 发送验证码
     * @Date: 2021/5/28 14:44
     * @param phone
     * @param typ
     * @Return: java.lang.String
     **/
    @Override
    public String sendCode( String phone,String typ) {

        //1、判断手机号是否存在？"手机号不存在，请先注册"
        UserBean user = userDao.findUserByPhone(phone);


            if(typ.equals("addUser") && user != null){
                return "此号码已注册过！！！ 请使用其他号码！！！";
            }


        //2、判断redis是否存在？"验证码已经发送过了"
        String key = typ+phone;
        if(redisTemplate.hasKey(key)){//存在
            return "验证码已经发送过了！！";
        }

        //3、调用短信接口发送
        String str = HttpClientUtil.sendMsg(phone);
        JSONObject parseObject = JSONObject.parseObject(str);
        int code = parseObject.getIntValue("code");
        if(code!=200){
            return "验证码发送失败！！！";
        }

        //4、发送成功：存入redis,设置5分钟过期时间
        String msgcode = parseObject.getString("obj");
        redisTemplate.opsForValue().set(key, msgcode, 10, TimeUnit.MINUTES);

        return "验证码发送成功！";

    }

    /**
     * @Author:程旭航
     * @Description: 快捷登录
     * @Date: 2021/5/28 14:44
     * @param phone
     * @param code
     * @param typ
     * @Return: java.lang.String
     **/
    @Override
    public HashMap<String, Object> quickLogin(String phone, String code,String typ) {
        HashMap<String, Object> map = new HashMap<String, Object>();

        String key = typ+phone;

        if(!redisTemplate.hasKey(key) ){
            map.put("string","请重新获取验证码！！！");
            map.put("bean",null);

            return map;
        }
        String s = (String) redisTemplate.opsForValue().get(key);
        if (!s.equals(code)){
            map.put("string","验证码错误！！");
            map.put("bean",null);
            return map;
        }

        UserBean user = userDao.findUserByPhone(phone);
        if(user==null){
            UserBean userBean = new UserBean();
            userBean.setPhone(phone);
            userBean.setUserPwd("123456");
            long time = new Date().getTime();
            String s1 = String.valueOf(time).substring(6);
            userBean.setUserName("飘飘_"+s1);
            userBean.setImg("https://img.meituan.net/avatar/7a3ba424ed43124a32918e6331a80f9d66523.jpg");

            try {
                // 生成一个MD5加密计算摘要
                MessageDigest md = MessageDigest.getInstance("MD5");
                // 计算md5函数
                md.update(userBean.getUserPwd().getBytes());
                // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
                // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
                //一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
                String s2 = new BigInteger(1, md.digest()).toString(16);
                userBean.setUserPwd(s2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*新增账号*/
            Integer  id=userDao.addUser(userBean);
            /*新增用户信息*/

            userDao.addUserInfo(userBean);
             user = userDao.findUserByPhone(phone);
        }

        map.put("string","登陆成功!!");
        map.put("bean",user);
        return map;
    }

    /**
     * @Author:程旭航
     * @Description: 账号登陆
     * @Date: 2021/5/28 14:45
     * @param userName
     * @param userPwd
     * @Return: java.lang.String
     **/
    @Override
    public  HashMap<String, Object>  login(String userName, String userPwd) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        UserBean user = userDao.findUserByName(userName);
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(userPwd.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            //一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
            String s2 = new BigInteger(1, md.digest()).toString(16);
            if (user == null || !user.getUserPwd().equalsIgnoreCase(s2)){
                map.put("string","账户或密码请核对后输入！！！");
                map.put("bean",null);

                return map;
            }
            ServletRequestAttributes requestAttributes = ( ServletRequestAttributes ) RequestContextHolder.getRequestAttributes();
            HttpSession session2 = requestAttributes.getRequest().getSession();

            session2.setAttribute("user",user);


            map.put("string","登陆成功!!");
            map.put("bean",user);



        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;

    }

    /**
     * @Author:程旭航
     * @Description: 修改密码
     * @Date: 2021/5/28 14:45
     * @param phone
     * @param userPwd
     * @Return: java.lang.String
     **/
    @Override
    public String upPwd(String phone,String userPwd) {
         userDao.upPwd( phone, userPwd);
        return "修改成功";
    }

    /**
     * @Author:程旭航
     * @Description: 新增账号
     * @Date: 2021/5/28 14:45
     * @param user
     * @param code
     * @param typ
     * @Return: java.lang.String
     **/
    @Override
    public String addUser(UserBean user, String code,String typ) {
        UserBean userss = userDao.findUserByPhone(user.getPhone());
        if (userss != null){
           return  "此手机账号已注册过";
        }

        HashMap<String, Object> map = quickLogin(user.getPhone(), code, typ);
        String s = (String) map.get("string");
        if (!s.equals("登陆成功!!")){
            return s;
        }
        long time = new Date().getTime();
        String s1 = String.valueOf(time).substring(6);
        user.setUserName("飘飘_"+s1);
        user.setImg("https://img.meituan.net/avatar/7a3ba424ed43124a32918e6331a80f9d66523.jpg");

        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(user.getUserPwd().getBytes());
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            //一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
            String s2 = new BigInteger(1, md.digest()).toString(16);
            user.setUserPwd(s2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*新增账号*/
        Integer  id=userDao.addUser(user);
        /*新增用户信息*/

        userDao.addUserInfo(user);
        return "注册成功！！";
    }

    /**
     * @Author:程旭航
     * @Description: 查看订单
     * @Date: 2021/5/28 14:45
     * @param phone
     * @param page
     * @param rows
     * @Return: java.util.List<com.jk.OrderBean>
     **/
    @Override
    public List<OrderBean> queryOrder(String phone, Integer page, Integer rows) {
        ArrayList<OrderBean> list = new ArrayList<OrderBean>();


        int a=0;
        if(page==1){
            String hashkey = "orderList";
            String key = "userphone_"+phone;
            List<OrderBean> list2 = (List<OrderBean>) redisTemplate.opsForHash().get(hashkey, key);

            if(list2 != null){
                for (OrderBean order2 : list2) {
                    order2.setState("未支付");
                    list.add(order2);
                    a++;
                }
            }

        }

    int sdf=0;
       if(page==1){
           rows=rows-a;
           sdf=(page-1)*rows;
       }
       else if(page>1){
            sdf=(page-1)*rows-a-1;
       }
        Query query = new Query();

        query.addCriteria(Criteria.where("phone").is(phone));

        query.with(Sort.by(Sort.Direction.DESC,"date"));
        query.skip(sdf).limit(rows);
        List<OrderBean> beans = mongoTemplate.find(query, OrderBean.class);
        if (beans.size()>0){
            for (OrderBean bean:beans) {
                //电影id
                Integer movieId = bean.getMovieId();
                //获取电影图片地址
               String img = userDao.queryImg(movieId);
                bean.setImg(img);
                list.add(bean);
            }
        }

        return list;
    }

    /*
     * @Author:程旭航
     * @Description: 修改用户信息
     * @Date: 2021/5/28 16:41
     * @param user
     * @Return: java.lang.String
     **/
    @Override
    public String updateUserInfo(UserInfo user) {

        int integer =userDao. queryUseryd(user.getId());

        userDao.upusername(integer ,user.getNickName());

        userDao. updateUserInfo(user);
        return "修改成功";
    }

    /*
     * @Author:程旭航
     * @Description: 查询用户
     * @Date: 2021/5/28 17:36
     * @param userId
     * @Return: com.jk.UserInfo
     **/

    @Override
    public UserInfo queryUserInfo(Integer userId) {
        UserInfo user=    userDao. queryUserInfo(userId);
        return user;
    }

    /**
     * @Author:程旭航
     * @Description:注销登录
     * @Date: 2021/5/30 14:24
     * @param
     * @Return: void
     **/
    @Override
    public void logout() {
        ServletRequestAttributes requestAttributes = ( ServletRequestAttributes ) RequestContextHolder.getRequestAttributes();
        HttpSession session2 = requestAttributes.getRequest().getSession();
        session2.removeAttribute("user");
    }

    /**
     * @Author:程旭航
     * @Description: 删除订单
     * @Date: 2021/5/30 19:47
     * @param orderId
     * @param phone
     * @Return: void
     **/
    @Override
    public void delOrder(String orderId, String phone) {
        String hashkey = "orderList";
        String key = "userphone_"+phone;
        List<OrderBean> list2 = (List<OrderBean>) redisTemplate.opsForHash().get(hashkey, key);
        for (int i = 0; i <list2.size() ; i++) {
            if (list2.get(i).getOrderId().equals(orderId)){
                list2.remove(i);
            }
        }
       redisTemplate.opsForHash().put(hashkey, key,list2);
    }

    @Override
    public OrderBean queeryOrder(String orderId, String state, String phone) {
        OrderBean orderBean = new OrderBean();
        if (state.equals("未支付")){
           String hashkey = "orderList";
           String key = "userphone_"+phone;
           List<OrderBean> list= (List<OrderBean>) redisTemplate.opsForHash().get(hashkey, key);
            for (OrderBean bean:list) {
                if (bean.getOrderId().equals(orderId)){
                    orderBean=bean;
                }
            }

       }else{
           Query query = new Query();

           query.addCriteria(Criteria.where("orderId").is(orderId));
            orderBean = (OrderBean) mongoTemplate.find(query, OrderBean.class);
       }



        return orderBean;
    }

    /**
     * @Author:程旭航
     * @Description: 查询订单
     * @Date: 2021/6/1 20:40
     * @param orderId
     * @Return: com.jk.OrderBean
     **/
    @Override
    public OrderBean queryDetails(String orderId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("orderId").is(orderId));
        List<OrderBean> beans = mongoTemplate.find(query, OrderBean.class);
        return beans.get(0);
    }


}
